#include "likou_algorithm.h"

typedef struct rec_child_str
{
	MY_U16 	len;
	MY_U8 	data[64];
} rec_child_str_t;


//计算字符串的子串
MY_U16 CalcTheChildStrOfString(MY_U8 *str, MY_U16 u16Len)
{
	MY_U16 	i, j = 0;
	MY_U16	u16StartIndex = 0;
	MY_U16	u16CalcLen = 0;
	MY_U16	u16Ret = 0;
	
	//采用插标法定位长度
	for (i=0; i<u16Len; i++)
	{
		//从标记位置开始检索
		for (j=u16StartIndex; j<i; j++)
		{
			if (str[i] != str[j])
			{
//				u16UnRepeatCnt++;
//				DBG_TRACE_INFO("j = %d | str[%d] = %c | u16UnRepeatCnt = %d", j, j, str[j], u16UnRepeatCnt);
			}
			else
			{
				u16CalcLen = i - u16StartIndex;
				u16StartIndex = i;
				
				DBG_TRACE_ERROR("xxxxx The Same Char i = %d | str[%d] = %c u16CalcLen = %d", i, j, str[j], u16CalcLen);
				break;
			}
		}
		
		u16Ret = (u16Ret > u16CalcLen) ? u16Ret : u16CalcLen;
		DBG_TRACE_INFO("------------------- str[%d] = %c | u16StartIndex = %d\n\n", i, str[i], u16StartIndex);
	}

	if (u16StartIndex == 0)
	{
		u16Ret = u16Len;
		DBG_TRACE_FAILED("The Str has no child!!\n");
	}

	DBG_TRACE_INFO("------------------- real_len = %d", u16Ret);
	return u16Ret;
}


//计算数组的值(去重)
MY_U16 CalcStrLen_WhithoutRepeat(MY_U8 *str, MY_U16 u16len)
{
	MY_U8	*rec_index = NULL;
	MY_U8 	*NewBuf = NULL;
	MY_U16	u16RetLen = 0;
	MY_U16	u16RepCnt = 0;
	MY_U16	i, j, k, x = 0;
	MY_U8	target_ch = '\0';
	MY_U8	flag = 0;
	
	rec_index = (MY_U8 *)malloc(u16len);
	NewBuf 	= (MY_U8 *)malloc(u16len);
	if ((NULL == rec_index) || (NULL == NewBuf))
	{
		DBG_TRACE_ERROR("malloc failed!!\n");
		return 0;
	}
	memset(rec_index, 0xFF, u16len);
	memset(NewBuf, '\0', u16len);
	DBG_TRACE_INFO("rec_index = %p | u16len = %d", rec_index, u16len);
	
	for (i=0; i<u16len; i++)
	{
		flag = 0;
		target_ch = str[i];
		DBG_TRACE_ERROR("i = %d target_ch = %c", i, target_ch);

		//检索是否在重复的下表buf中
		for (x=0; x<u16RepCnt; x++)
		{
			if (i == rec_index[x])
			{
				DBG_TRACE_ERROR("xxxxxxxxx index = %d\n", rec_index[x]);
				flag = 1;
				break;
			}
		}

		//检索后面的字符串
		for (j=i+1; (j<u16len) && (flag==0); j++)
		{
			if (target_ch == str[j])
			{
				//记录重复的下标
				rec_index[u16RepCnt++] = j;
				DBG_TRACE_INFO("rec_index[%d] = %d", u16RepCnt-1, rec_index[u16RepCnt-1]);
			}
		}
	}

	DBG_TRACE_INFO("u16RepCnt = %d", u16RepCnt);
	for (i=0, k=0; i<u16len; i++)
	{
		for (j=0; j<u16RepCnt; j++)
		{
			if (i == rec_index[j])
			{
				DBG_TRACE_INFO("-------------> i = %d rec_index[%d] = %d", i, j, rec_index[j]);
				break;
			}
		}

		//当都不存在重复时记录
		if (u16RepCnt == j)
		{
			NewBuf[k++] = str[i];
			DBG_TRACE_INFO("-------------------- NewBuf[%d] = %c\n\n", k-1, NewBuf[k-1]);
		}
	}
	
	u16RetLen = u16len - u16RepCnt;	
	DBG_TRACE_ERROR(" k = %d | NewBuf = %s", k, NewBuf);
	DBG_TRACE_ERROR("u16RetLen = %d\n", u16RetLen);

out:
	free(rec_index);
	free(NewBuf);
	rec_index 	= NULL;
	NewBuf 		= NULL;
	return u16RetLen; 
}


